package logic

import (
	"context"
	"errors"
	"house/cache"
	pkgimport "house/pkg"
	"math/rand"
	"strconv"
	"time"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *houserpc.SendSmsRequest) (*houserpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	code := rand.Intn(9000) + 1000
	count, _ := cache.Rdb.Get(l.ctx, "number"+in.Mobile).Int()
	if count > 1 {
		return nil, errors.New("一个手机号一分钟只能发送一条")
	}
	sms, err := pkgimport.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}
	cache.Rdb.Set(l.ctx, "send"+in.Mobile, code, time.Minute*5)
	cache.Rdb.Incr(l.ctx, "number"+in.Mobile)
	cache.Rdb.Expire(l.ctx, "number"+in.Mobile, time.Minute*1)
	return &houserpc.SendSmsResponse{}, nil
}
